package com.app.couponsharelife.ui.adapter

import androidx.databinding.DataBindingUtil
import androidx.constraintlayout.widget.ConstraintLayout
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.databinding.HeadlineListPicItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.utils.AppUtils

/**
 * Created by guluwa on 2018/11/23.
 */
class HeadlinePicsAdapter(private val list: List<Any>,
                          private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.headline_list_pic_item, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        val width = ((AppUtils.getDisplayMetrics(holder.itemView.context).widthPixels * 0.91
                - AppUtils.dip2px(holder.itemView.context, 15f)) / 3).toInt()
        val layoutParams = ConstraintLayout.LayoutParams(width, width)
        layoutParams.topMargin = AppUtils.dip2px(holder.itemView.context, 5f)
        layoutParams.marginEnd = AppUtils.dip2px(holder.itemView.context, 5f)
        holder as ViewHolder
        Glide.with(holder.itemView).asBitmap()
                .apply(RequestOptions().placeholder(R.drawable.ic_good_place_holder).transform(RoundedCorners( 10)))
                .load(list[position])
                .into(holder.databinding.ivSharePic)
        holder.databinding.ivSharePic.layoutParams = layoutParams
        holder.databinding.ivSharePic.adjustViewBounds = false
    }

    inner class ViewHolder(val databinding: HeadlineListPicItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.ivSharePic.setOnClickListener {
                if (adapterPosition != -1)
                    listener.click(0, adapterPosition)
            }
        }
    }
}